import React, { useState  ,useEffect} from 'react';
import { HeaderDiv } from '../style'
import { SearchOutlined, PlusCircleOutlined  } from '@ant-design/icons';
import { Link } from 'react-router-dom'
import { getStorage } from '@/utils/LocalStorage.js'
import {supplierMock} from "@/model/loginModel"

import { Table, Input, Button,InputNumber, Popconfirm, Form, Typography, Row, Col } from 'antd';
const originData = [];

const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `Please Input ${title}!`,
              },
            ]}
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };
const Index = () => {
  const originData = getStorage('users')?JSON.parse(getStorage('users')):[]
 

    const [form] = Form.useForm();
    // const [expand, setExpand] = useState(false);
    const [data, setData] = useState(originData);
    const [editingKey, setEditingKey] = useState('');
    const [mocklist , setLists] = useState([]);
    async function setSupplierMock(){
      let res = await supplierMock()
      res= res.data.data;
      let lists = [...res , ...originData]
      setLists(lists)
      setData(lists)
    }
    
    useEffect(()=>{
      // const originData = getStorage('users')?JSON.parse(getStorage('users')):[]
      setData(originData)
      setSupplierMock()
    },[])

    //

  
    const onFinishseave = (values) => {
      console.log('Received values of form: ', values);
    };
    //
    const isEditing = (record) => record.key === editingKey;
  
    const edit = (record) => {
      form.setFieldsValue({
        name: '',
        age: '',
        address: '',
        ...record,
      });
      setEditingKey(record.key);
    };
  
    const cancel = () => {
      setEditingKey('');
    };
  
    const save = async (key) => {
      try {
        const row = await form.validateFields();
        const newData = [...data];
        const index = newData.findIndex((item) => key === item.key);
  
        if (index > -1) {
          const item = newData[index];
          newData.splice(index, 1, { ...item, ...row });
          setData(newData);
          setEditingKey('');
        } else {
          newData.push(row);
          setData(newData);
          setEditingKey('');
        }
      } catch (errInfo) {
        console.log('Validate Failed:', errInfo);
      }
    };
  
    const columns = [
      {
        title: '供应商编号',
        dataIndex: 'numbering',
        // width: '13%',
        editable: true,
    },
    {
        title: '供应商来源',
        dataIndex: 'rootIn',
        // width: '13%',
        editable: true,
    },
    {
        title: '单位名称',
        dataIndex: 'compony',
        // width: '10%',
        editable: true,
    },
    {
        title: '品牌',
        dataIndex: 'logo',
        // width: '15%',
        editable: true,
    },
    {
        title: '引进负责人',
        dataIndex: 'name',
        // width: '15%',
        editable: true,
    },
    // {
    //     title: '日期',
    //     dataIndex: 'time',
    //     // width: '15%',
    //     editable: true,
    // },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => {
          const editable = isEditing(record);
          return editable ? (
              <span>
                  <a
                      href="javascript:void(0);"
                      onClick={() => save(record.key)}
                      style={{
                          marginRight: 8,
                      }}
                  >
                      保存
      </a>
                  <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
                      <a>取消</a>
                  </Popconfirm>
              </span>
          ) : (
              <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
                  修改
              </Typography.Link>
          );
      },
  },
    ];

    const mergedColumns = columns.map((col) => {
      if (!col.editable) {
        return col;
      }
  
      return {
        ...col,
        onCell: (record) => ({
          record,
          inputType: col.dataIndex === 'age' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: isEditing(record),
        }),
      };
    });
    return (
      <HeaderDiv>

    
      {/* 头部 */}
      <div className='header'>
          <span>采购管理</span>
          <span>/</span>
          <strong>供应商管理</strong>
          <hr />
      </div>
      {/* input框 */}
      <div className='formMine'>
          <div className='formone'>
          <Form
      form={form}
      name="advanced_search"
      className="ant-advanced-search-form"
      onFinish={onFinishseave}
    >
          <Row gutter={24}>
            <Col span={8}   key={1}>
            <Form.Item
              name={`numbering`}
              label={`供应商编号 `}
              
              rules={[
                {
                  message: 'Input something!',
                },
              ]}
            >
              <Input placeholder="placeholder" />
            </Form.Item>
            </Col>
          
         
            <Col span={8} key={2}>
            <Form.Item
              name={`rootIn`}
              label={`供应商来源 `}
              rules={[
                {
                  message: 'Input something!',
                },
              ]}
            >
              <Input placeholder="placeholder" />
            </Form.Item>
            </Col>
            <Col span={8} key={3}>
            <Form.Item
              name={`compony`}
              label={`单位名称 `}
              rules={[
                {
                  message: 'Input something!',
                },
              ]}
            >
              <Input placeholder="placeholder" />
            </Form.Item>
            </Col>
            <Col span={8} key={4}>
            <Form.Item
              name={`logo`}
              label={`品牌 `}
              rules={[
                {
                  message: 'Input something!',
                },
              ]}
            >
              <Input placeholder="placeholder" />
            </Form.Item>
            </Col>
            <Col span={8} key={5}>
            <Form.Item
              name={`operation`}
              label={`引进负责人 `}
              rules={[
                {
                  message: 'Input something!',
                },
              ]}
            >
              <Input placeholder="placeholder" />
            </Form.Item>
            </Col>
            <Col span={8} key={6}>
            <Form.Item
              name={`field`}
              label={`操作 `}
              rules={[
                {
                  message: 'Input something!',
                },
              ]}
            >
              <Input placeholder="placeholder" />
            </Form.Item>
            </Col>
          </Row>
          
          
         
          
          
          {/* 添加搜索按钮 */}
          <Form.Item>
          <div className="button">
              <Button className="buttonSearch" type="primary" htmlType="submit"     icon={<SearchOutlined />} size='large'>
                  搜索
              </Button>
              <Link to='/home/AddSupplier'>
                  <Button className='buttonAdd' type="primary" icon={<PlusCircleOutlined />} size='large'>
                      添加
                  </Button>
              </Link>
          </div>
          </Form.Item>
          </Form>
          </div>
          <hr />
      </div>
        <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          bordered
          dataSource={data}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{
            onChange: cancel,
          }}
        />
      </Form>
      </HeaderDiv>
    );
}

export default Index;
